package com.zy.propertysource.demo.config;

import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertySource;
import org.springframework.core.env.StandardEnvironment;


public class IpValuePropertySource extends PropertySource<IPUtil> {

    public static final String IPUTIL_PROPERTY_SOURCE_NAME = "ipUtil";

    private static final String PREFIX = "ipUtil.";

    public IpValuePropertySource(String name) {
        super(name, new IPUtil());
    }

    @Override
    public Object getProperty(String name) {
        if (!name.startsWith(PREFIX)) {
            return null;
        }
        return getAddress(name.substring(PREFIX.length()));
    }

    private String getAddress(String type){
        if("local".equals(type)){
            return getSource().getAddress();
        }

        return "0.0.0.0";
    }

    public static void addToEnvironment(ConfigurableEnvironment environment) {
        environment.getPropertySources().addAfter(
                StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME,
                new IpValuePropertySource(IPUTIL_PROPERTY_SOURCE_NAME));
    }
}
